#ifndef CAMERA_THREAD_H
#define CAMERA_THREAD_H

#include <QThread>
#include <QImage>
#include <linux/videodev2.h>

class CameraThread : public QThread
{
    Q_OBJECT
public:
    explicit CameraThread(QObject *parent = nullptr);
    ~CameraThread();

    void stopCapture();
    void setDevice(const QString &device);

signals:
    void frameReady(const QImage &image);
    void errorOccurred(const QString &message);

protected:
    void run() override;

private:
    struct Buffer {
        void *start;
        size_t length;
    };

    bool initCamera();
    void cleanup();
    QImage convertYUYVToRGB(const unsigned char *yuyv, int width, int height);

    bool m_running = false;
    QString m_device;
    int m_v4l2Fd = -1;
    int m_width = 640;
    int m_height = 480;
    Buffer *m_buffers = nullptr;
    unsigned int m_nBuffers = 0;
    unsigned int m_pixelFormat = V4L2_PIX_FMT_YUYV;
};

#endif // CAMERA_THREAD_H
